package org.wupuser.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupuser.model.Friend;
import org.wupuser.model.User;

import java.util.List;

@Repository
public interface FriendRepository extends JpaRepository<Friend, Long> {
	@Query(value = "select u from User u join Friend f on u.id = f.userId where f.userId = :userId and f.status = true and u.isDeleted = false ")
	List<User> findUsersAllFriendById(
		@Param("userId") Long userId
	                                 );
	
	@Query(value = "select f from Friend f where f.friendId = :friendId and f.status = false ")
	List<Friend> findRequest(
		@Param("friendId") Long friendId
	                        );
	
	@Transactional
	@Modifying
	@Query(value = "insert  into Friend (createTime,confirmTime,userId,friendId,status) values (:#{#friend.createTime},:#{#friend.confirmTime},:#{#friend.userId},:#{#friend.friendId},:#{#friend.status})")
	void sendRequestOrConfirmTowWay(Friend friend);
	
	@Transactional
	@Modifying
	@Query(value = "update Friend f set f.status = true,f.confirmTime = :#{#friend.confirmTime} where f.userId = :#{#friend.userId} and f.friendId = :#{#friend.friendId}")
	void confirmRequestFromFriend(
		Friend friend
	                             );
	
	@Transactional
	@Modifying
	@Query(value = "delete from Friend f where f.userId = :userId and f.friendId = :friendId and f.status = true ")
	void deleteFriend(
		@Param("userId") Long userId,
		@Param("friendId") Long friendId
	                 );
}
